package com.ruoyi.mall.app.service.impl;

import com.ruoyi.mall.app.service.DtsCommentService;
import com.ruoyi.mall.common.domain.DtsComment;
import com.ruoyi.mall.common.domain.DtsOrder;
import com.ruoyi.mall.common.domain.DtsOrderGoods;
import com.ruoyi.mall.common.mapper.DtsCommentMapper;
import com.ruoyi.mall.common.mapper.DtsOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DtsCommentServiceImpl implements DtsCommentService {

    @Autowired
    private DtsCommentMapper dtsCommentMapper;

    @Autowired
    private DtsOrderMapper dtsOrderMapper;

    @Override
    public List<DtsComment> selectDtsCommentList(DtsComment dtsComment) {
        return dtsCommentMapper.selectDtsCommentList(dtsComment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDtsComment(DtsComment dtsComment) {
        // 1. 插入评论并获取生成的评论ID
        int insertCount = dtsCommentMapper.insertDtsComment(dtsComment);
        if (insertCount <= 0) {
            throw new RuntimeException("评论添加失败");
        }
        Long commentId = dtsComment.getId(); // MyBatis回填自增ID

        // 2. 更新订单状态为403（假设valueId是订单ID）
        DtsOrder order = new DtsOrder();
        order.setId(dtsComment.getOrderId()); // 设置订单ID
        order.setOrderStatus("403"); // 设置状态码
        int updateOrderStatus = dtsOrderMapper.updateDtsOrder(order);
        if (updateOrderStatus <= 0) {
            throw new RuntimeException("订单状态更新失败");
        }

        // 3. 更新订单商品表的comment字段（假设productId是订单商品ID）
        DtsOrderGoods orderGoods = new DtsOrderGoods();
        orderGoods.setId(dtsComment.getOrderGoodsId()); // 设置订单商品ID
        orderGoods.setComment(commentId); // 设置评论ID
        int updateGoodsComment = dtsCommentMapper.updateDtsOrderGoodsComment(orderGoods);
        if (updateGoodsComment <= 0) {
            throw new RuntimeException("订单商品评论更新失败");
        }

        return insertCount;
    }
}
